<?php

// // +--------------------------------- 商品数据控制器 -------------------------------------
namespace app\controller;

use app\BaseController;
use app\common\urils\Ch;
use app\dto\R;
use app\model\Goods;
use app\model\GoodsDetailImgs;
use app\model\GoodsLabels;
use app\model\GoodsSlidshows;
use app\model\GoodsSpecifications;
use app\model\GoodsSpecis;
use app\model\UserCollections;

use app\validate\GoodsValidate;
use think\facade\Log;
use think\facade\Request;
use think\facade\Validate;

class GoodsController extends BaseController
{

    // 根据商品ID获取商品信息
    public function getGoodsById()
    {
        // 接收参数
        $goodsId = Request::get('goodsId');

        // 参数验证
        if (empty($goodsId)) {
            return json(R::error("商品ID不能为空"));
        }

        // 查询商品信息， 关联查询
        $goodsInfo = Goods::where('goods_id', $goodsId)
            ->with([
                'labels',
                'slideshows',
                'detailImgs',
                'specificationsWithValues'
            ])
            ->find();

        // 返回成功响应
        return json(R::result(1, '获取成功', $goodsInfo));
    }

    // 根据商品名称获取商品信息（模糊搜索 - 搜索提示）, 接收参数：goodsName ， 返回商品ID和商品名称
    public function getGoodsByName()
    {
        // 接收参数
        $goodsName = Request::get('goodsName');

        // 参数验证
        if (empty($goodsName)) {
            return json(R::error("无提示词"));
        }

        // 查询商品信息
        $goodsInfos = Goods::where('goods_name', 'like', '%' . $goodsName . '%')
            ->field('goods_id, goods_name')
            ->select();

        // 返回成功响应
        return json(R::result(1, '获取成功', $goodsInfos));
    }

    // 处理商品收藏 和 取消收藏 ，接收post参数：userId， goodsId 和 ops（收藏传入start ， 取消收藏传入disStart）
    public function handleCollect()
    {
        // 接收参数
        $param = Request::only(['userId', 'goodsId', 'ops']);

        // 参数验证
        if (empty($param['userId']) || empty($param['goodsId']) || empty($param['ops'])) {
            return json(R::error("参数错误"));
        }

        // 根据操作类型进行处理
        if ($param['ops'] === 'start') {
            // 收藏商品，根据用户id和商品id进行查询，如果没有在创建收藏关系
            $collection = UserCollections::where('user_id', $param['userId'])
                ->where('goods_id', $param['goodsId'])
                ->find();

            if ($collection && $collection->status == 1) {
                // 提示已收藏
                return json(R::error("已收藏该商品"));
            }
            if ($collection) {
                // 存在，将收藏状态改为1
                UserCollections::update(['status' => 1], ['user_id' => $param['userId'], 'goods_id' => $param['goodsId']]);
                return json(R::result(1, "收藏成功", true));
            } else {
                // 不存在，创建新的收藏记录
                UserCollections::create([
                    'user_id' => $param['userId'],
                    'goods_id' => $param['goodsId'],
                    'status' => 1, // 收藏状态，1表示已收藏
                    'create_time' => date('Y-m-d H:i:s'),
                ]);
                return json(R::result(1, "收藏成功", true));
            }
        } elseif ($param['ops'] == 'disStart') {
            // 取消收藏商品，找出收藏记录，将收藏状态改为1
            $collection = UserCollections::where('user_id', $param['userId'])
                ->where('goods_id', $param['goodsId'])
                ->find();

            if ($collection) {
                // 存在，将收藏状态改为0
                UserCollections::update(['status' => 0], ['user_id' => $param['userId'], 'goods_id' => $param['goodsId']]);
                // $collection->update(['status' => 0]);
                return json(R::result(1, "取消收藏成功", true));
            } else {
                // 不存在，返回错误信息
                return json(R::error("未收藏该商品"));
            }
        } else {
            return json(R::error("操作类型错误"));
        }
    }


    /**
     * 商品列表视图组件获取商品数据
     * @return \think\response\Json
     */
    public function getGoodsData()
    {
        // 接收参数
        $param = Request::only(['showType', 'typeValue', 'page', 'size']);

        // 参数验证
        $validate = new GoodsValidate();
        if (!$validate->check($param)) {
            return json(['code' => 400, 'msg' => $validate->getError(), 'data' => null]);
        }

        // 构造查询对象
        $query = Goods::where('1=1');

        // 根据showType判断如何过滤商品数据
        switch ($param['showType']) {
            case 'index':
                // 首页推荐商品
                $query = $query->where('recommend', true);
                break;
            case 'type':
                // 根据类型过滤
                $query = $query->where('type', $param['typeValue']);
                break;
            case 'search':
                // 根据goodsName模糊查询
                $query = $query->whereLike('goods_name', '%' . $param['typeValue'] . '%');
                break;
            case 'store':
                // 根据店铺ID过滤
                $query = $query->where('owner_store_id', $param['typeValue']);
                break;
            default:
                // 默认不加过滤条件
                break;
        }

        // 获取总记录数
        $count = $query->count();

        // 处理分页参数
        $page = isset($param['page']) ? intval($param['page']) : 1;
        $size = isset($param['size']) ? intval($param['size']) : 8; // 默认每页8条

        // 查询商品数据并分页
        $goodsInfos = $query->with([
            'labels',
            'slideshows',
            'detailImgs',
            'specificationsWithValues'
        ])->page($page, $size)->select();
        // $goodsInfos = $query->page($page, $size)->select();

        // 查询商品的详情图，标签，轮播图 和 规格数据


        // 构造返回数据
        $data = [
            'count' => $count,
            'goodsInfos' => $goodsInfos
        ];

        // 返回成功响应
        return json(R::result(1, '获取成功', $data));
    }

    // ========== 后台管理端相关接口 ==========
    // 管理端获取商品列表数据
    public function getGoodsList()
    {
        // 接收参数
        $param = Request::only(['page', 'size', 'keyword']);

        // 构造查询对象
        $query = Goods::where('1=1');

        // 处理分页参数
        $page = isset($param['page']) ? intval($param['page']) : 1;
        $size = isset($param['size']) ? intval($param['size']) : 8; // 默认每页8条

        // 统计商品总数
        $count = Goods::whereLike("goods_name", '%' . $param['keyword'] . '%')->count();

        // 查询商品数据并分页
        $goodsInfos = $query->with([
            'labels',
            'slideshows',
            'detailImgs',
            'specificationsWithValues'
        ])
            ->whereLike('goods_name', '%' . $param['keyword'] . '%')
            ->page($page, $size)->select();

        // 构造返回数据
        $data = [
            'count' => $count,
            'goodsInfos' => $goodsInfos
        ];

        // 返回成功响应
        return json(R::result(1, '获取成功', $data));
    }


    // 管理端：新增商品（获取商品的全部数据，在此进行多表信息添加）
    public function addGoodsInfo()
    {
        // 获取前端传入数据
        $data = Request::post();

        // 新增商品基本信息
        $addRes = Goods::create($data);

        // 新增商品的依赖表
        // 获取商品ID
        $goodsId = $data["goods_id"];

        // ========  新增商品详情图 ========

        $details = $data["detailImgs"];
        $addDetailData = [];
        foreach ($details as $detailItem) {
            // 构造实例
            $tempObj = [
                "goods_id" => $goodsId,
                "image_url" => $detailItem
            ];
            $addDetailData[] = $tempObj;
        }
        (new GoodsDetailImgs())->saveAll($addDetailData);

        // ========  执行标签新增 ========

        $labels = $data["labels"];
        $addLableData = [];
        foreach ($labels as $labelItem) {
            // 构造实例
            $tempObj = [
                "goods_id" => $goodsId,
                "label" => $labelItem['label']
            ];
            $addLableData[] = $tempObj;
        }
        // 执行新增
        (new GoodsLabels())->saveAll($addLableData);

        //  ======== 新增商品轮播图 ========

        $slides = $data["slideshows"];
        $addSlidData = [];
        foreach ($slides as $slidItem) {
            // 构造实例
            $tempObj = [
                "goods_id" => $goodsId,
                "image_url" => $slidItem
            ];
            $addSlidData[] = $tempObj;
        }
        // 执行轮播图新增
        (new GoodsSlidshows())->saveAll($addSlidData);


        // ======== 执行规格项表新增 ========
        $speciItem = $data["specificationsWithValues"];

        // 存储规格项的ID列表
        $speciItemIds = [];

        // 遍历并添加规格项
        foreach ($speciItem as $speci) {
            // 生成唯一ID
            $uniqueId = Ch::generateUniqueId("sp");

            // 存储规格项名称与ID的对应关系
            $speciItemIds[$speci['speci_name']] = $uniqueId;

            // 添加规格项
            $speciData = [
                "id" => $uniqueId, 
                "goods_id" => $goodsId,
                "speci_name" => $speci['speci_name']
            ];

            // 检查数据
            Log::info('规格项数据: ' . json_encode($speciData));

            $speciModel = new GoodsSpecifications($speciData);
            $speciModel->save();

            // ======== 立即添加对应的规格项值 ========
            $addSpeciValues = [];
            foreach ($speci['specis'] as $item) {
                $addSpeciValues[] = [
                    "specification_id" => $uniqueId,  // 使用生成的字符串ID
                    "specis_value" => $item['specis_value'],
                    "price" => $item['price']
                ];
            }

            if (!empty($addSpeciValues)) {
                // 检查数据
                Log::info('规格项值数据: ' . json_encode($addSpeciValues));

                (new GoodsSpecis)->saveAll($addSpeciValues);
            }
        }

        return json(R::ok("新增数据成功"));
    }


    // 管理端：编辑商品
    /**
     * 编辑商品信息
     * @return JSON
     */
    public function edit()
    {
        // 获取请求数据
        $data = $this->request->post();
        
        // 验证商品数据
        $validate = Validate::rule([
            'id'             => 'require|number',
            'goods_name'     => 'require|max:200',
            'inventory'      => 'require|number|egt:0',
            'sale_volume'    => 'number|egt:0',
            'cover'          => 'require|max:255',
            'price'          => 'require|float|egt:0',
            'owner_store_id' => 'require|max:50',
            'recommend'      => 'boolean',
            'type'           => 'require|max:50',
            'sort'           => 'number|egt:0',
        ]);
        
        // 验证失败返回错误信息
        if (!$validate->check($data)) {
            return json(R::error("参数错误：" . $validate->getError()));
        }
        
        try {
            // 查询商品是否存在
            $goods = Goods::find($data['id']);
            if (!$goods) {
                return json(R::error("商品不存在"));
            }
            
            // 商品ID是否重复（排除自身）
            if ($data['goods_id'] !== $goods->goods_id) {
                $exist = Goods::where('goods_id', $data['goods_id'])
                    ->where('id', '<>', $data['id'])
                    ->find();
                if ($exist) {
                    return json(R::error("商品ID已存在"));
                }
            }
            
            // 更新商品信息
            $goods->save([
                'goods_id'       => $data['goods_id'],
                'goods_name'     => $data['goods_name'],
                'inventory'      => $data['inventory'],
                'sale_volume'    => $data['sale_volume'],
                'cover'          => $data['cover'],
                'price'          => $data['price'],
                'owner_store_id' => $data['owner_store_id'],
                'recommend'      => (bool)$data['recommend'],
                'type'           => $data['type'],
                'sort'           => $data['sort'],
            ]);
            
            return json(R::ok("商品信息更新成功"));
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('商品编辑异常：' . $e->getMessage());
            return json(R::error("商品编辑失败"));
        }
    }

    // 删除商品
    public function delete()
    {
        // 接收参数
        $goodsId = Request::post('goodsId');

        // 参数验证
        if (empty($goodsId)) {
            return json(R::error("商品ID不能为空"));
        }

        // 删除商品
        $goods = Goods::where('goods_id', $goodsId)->find();
        if (!$goods) {
            return json(R::error("商品不存在"));
        }

        // 删除商品:根据goods_id字段删除
        // 先删除商品的依赖表数据
        GoodsDetailImgs::where('goods_id', $goodsId)->delete();
        GoodsLabels::where('goods_id', $goodsId)->delete();
        GoodsSlidshows::where('goods_id', $goodsId)->delete();
        GoodsSpecifications::where('goods_id', $goodsId)->delete();

        // 根据goods_id查询处规格项id，再根据规格项id删除规格项值
        $specifications = GoodsSpecifications::where('goods_id', $goodsId)->select();
        foreach ($specifications as $specification) {
            // 删除规格项值
            GoodsSpecis::where('specification_id', $specification->id)->delete();
        }

        // 执行商品删除
        $goods->delete();

        // 返回成功响应
        return json(R::ok("商品删除成功"));
    }
}
